class Room{
    constructor(game,id){
        this.game = game;
        this.id = id;
        this.users = [];
        this.gameData = {};
        this.data = {};
        this.data.data = {};
        this.data.users = {
            '0':{point:{x:-200,y:0},direction:{x:0,y:0}},
            '1':{point:{x:200,y:0},direction:{x:0,y:0}},
        };
        this.frameData = [];
        this.frameTime = 0
    }

    frameUpdate(dt){
        this.frameTime += dt;
        this.broadcast('frame',{t:this.frameTime,v:this.frameData});
        this.frameData = [];
    }

    sceneInfo(){
        return {users:this.users,data:this.data}
    }

    onUserEnter(user){
        this.sendToUser(user,'join',{})
        user.pid = this.users.length;
        this.users.push(user);

    }
    onUserExit(user){
        var idx = this.users.findIndex(item=>{return user.id == item.id})
        if(idx >= 0){
            this.users.splice(idx,1);
            console.log('用户掉线，剩余玩家:',this.users.length);
        }
        // if(this.users.length > 0){
        this.broadcast('userExit',user);
        // } else {
        //     this.game.destroyRoom(this);
        // }
    }
    assignment(a,b){
        for(var k in b){
            if(!a[k]){
                a[k] = typeof(b[k]) == 'object' ? {} : [];
            }
            Object.assign(a[k],b[k]);
        }
    }
    message(user,data){
        console.log('message:',data,this.users.length);
        if(data.ge == 'ready'){
            for(let i=0; i<this.users.length; i++){
                if(this.users[i].id == user.id){
                    this.gameSend(user,'ready',this.sceneInfo());
                } else {
                    this.gameSend(this.users[i],'newUser',{user:user,data:this.data.users[user.id]});
                }
            }
        } else if(data.ge == 'suser'){
            this.assignment(this.data.users[user.id],data.v);
        } else if(data.ge == 'sdata'){
            this.assignment(this.data.data,data.v);
            // Object.assign(this.data.data,data.v);
        } else if(data.ge == 'frame'){
            this.frameData.push(data.v);
        } else {
            this.gameBroadcast(data.ge,data.v);
        }
    }
    gameSend(user,e,v){
        this.game.send(user.id,{e:'game',v:{ge:e,v:v}});
    }
    sendToUser(user,e,v){
        this.game.send(user.id,{e:e,v:v});
    }
    gameBroadcast(e,v){
        for(let i=0; i<this.users.length; i++){
            this.gameSend(this.users[i],e,v)
        }
    }
    broadcast(k,v){
        for(let i=0; i<this.users.length; i++){
            this.sendToUser(this.users[i],k,v)
        }
    }
}



module.exports = Room;